<template>
  <basic-container>
    <!-- 头部搜索栏 -->
    <div class="search-wrap">
      <div class="merchant" style="display: inline-block">
        选择商家：
        <el-select
          filterable
          remote
          :remote-method="remoteMerchant"
          v-model="merchantId"
          @change="changeMerchant"
          placeholder="请选择"
        >
          <el-option
            v-for="(item,index) in merchantList"
            :key="index"
            :label="item.merchantName"
            @change="changeMerchant"
            :value="item.merchantId"
          />
        </el-select>
      </div>
      <div class="shop" style="display: inline-block;margin-left: 20px;">
        选择店铺：
        <el-select
          filterable
          remote
          :remote-method="remoteShop"
          v-model="shopId"
          @change="changeShop"
          placeholder="请选择"
        >
          <el-option
            v-for="(item,index) in shopList"
            :key="index"
            :label="item.name"
            :value="item.shopId"
          />
        </el-select>
      </div>
      <div class="tool-btns">
        <category_import
          ref="categoryImport"
          style="display: inline-block;margin-right: 20px"
          :inputShopId="shopId"
        />
        <el-button type="primary" @click="toCSale" :disabled="toSaleBtnFlag" v-show="currentMerchant.pdsType==1">一键同步商城</el-button>
      </div>
    </div>
    <!-- 表格展示部分   -->
    <avue-crud
      :data="goodsCategories"
      :option="tableOption"
      @refresh-change="refreshTable"
      @search-change="searchChange"
    >
      <!-- 新增分类    -->
      <template slot-scope="scope" slot="menuLeft">
        <el-button type="primary" icon="el-icon-plus" size="small" @click.stop="addGoodsCate">新增分类</el-button>
      </template>
      <!-- 分类图标 -->
      <template slot="logo" slot-scope="scope">
        <img :src="scope.row.logo" class="category-logo" v-if="scope.row.logo" />
      </template>

      <!-- 批量上下架 -->
      <template slot="batch" slot-scope="scope">
        <el-switch
          v-model="scope.row.status"
          :disabled="batchObj[scope.row.id]"
          :active-value="'1'"
          :inactive-value="'0'"
          @change="modifyStatus(scope.row.status , scope.row.id)"
        ></el-switch>
      </template>

      <!-- 是否显示 -->
      <template slot="show" slot-scope="scope">
<!--        {{test}}-->
        <el-switch
          v-model="scope.row.categoryType"
          :disabled="showObj[scope.row.id]"
          :active-value="'1'"
          :inactive-value="'0'"
          @change="changeShow(scope.row.categoryType , scope.row.id)"
        ></el-switch>
      </template>

      <!-- 新增子分类 -->
      <template slot="children" slot-scope="scope">
        <el-button
          type="text"
          v-if="scope.row.parentId == 0"
          @click.stop="addSubGoodsCate(scope.row)"
        >新增</el-button>
      </template>

      <!-- 操作功能 -->
      <template slot-scope="scope" slot="menu">
        <el-button
          type="primary"
          icon="el-icon-check"
          size="small"
          @click.stop="editGoodsCate(scope.row)"
        >修改</el-button>
        <el-button
          type="danger"
          icon="el-icon-check"
          size="small"
          @click.stop="delGoodsCate(scope.row)"
        >删除</el-button>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import { fetchList as getmerchantList } from "../../api/manage/merchant";
import { fetchList } from "../../api/manage/shop";
import { getCategoryTree, deleteCategory } from "../../api/goods/goodscategory";
import { tableOption } from "../../const/crud/supply/goods_category";
import { changeCategoryStatus, offGoodsByCate } from "../../api/goods/category";
import { categoryToSaleC } from "../../api/salec/salecproduct";
import category_import from "@/components/goods/excel_import/goods_category_import";

export default {
  name: "index",
  components: {
    category_import
  },
  data() {
    return {
      goodsName: "",
      merchantList: [],
      currentMerchant: {},
      shopList: [],
      merchantId: "",
      shopId: "",
      goodsCategories: [],
      tableOption: tableOption,
      fly: 1,
      toSaleBtnFlag: false,
      batchObj: {},
      showObj: {},
    };
  },
  created() {
    this.getMerchantList({ status: 2 });
  },

  methods: {
    //一键同步商城
    toCSale() {
      this.toSaleBtnFlag = true;
      const params = {
        shopId: this.shopId
      };
      categoryToSaleC(params).then(res => {
        if(res.data.data) {
          this.$message.success("同步成功");
        }else {
          this.$message.error("同步失败")
        }
        this.toSaleBtnFlag = false;
      });
    },
    //获取供应商列表
    getMerchantList(param = {}) {

      getmerchantList(param).then(res => {
        this.merchantList = res.data.data.records;
        this.merchantId = res.data.data.records[0].merchantId;
        this.getShopList();
      });
    },
    remoteMerchant(name = null) {
      let query = {
        merchantName: name,
        status: 2
      };
      getmerchantList(query).then(res => {
        this.merchantList = res.data.data.records;
      });
    },
    //改变merchantId
    changeMerchant() {
      let that = this;
      this.merchantList.forEach(function(item, index) {
        if (item.merchantId === that.merchantId) {
          that.currentMerchant = item;
        }
      });
      let params = {
        status: 2,
        merchantId: this.merchantId,
        name: name,
      };
      fetchList(params).then(res => {
        this.shopList = res.data.data.records;
        if (res.data.data.records.length == 0) {
          this.$message.warning("没有店铺");
          this.shopId = "";
          this.goodsCategories = [];
        }
        setTimeout(() => {
          this.shopId = this.shopList[0].shopId;
          this.getGoodsCategoryList();
        },100);
      });
    },
    //获取店铺列表
    getShopList() {
      let params = {};
      params.status = 2;
      params.merchantId = this.merchantId;
      // params.shopId = this.shopId;
      fetchList(params).then(res => {
        this.shopList = res.data.data.records;
        this.shopId = res.data.data.records[0].shopId;
        this.getGoodsCategoryList();
      });
    },
    remoteShop(name = null) {
      let params = {
        status: 2,
        merchantId: this.merchantId,
        name: name,
      };
      fetchList(params).then(res => {
        this.shopList = res.data.data.records;
      });
    },
    //改变shopID
    changeShop() {
      this.getGoodsCategoryList();
    },
    // 获取商品分类列表
    getGoodsCategoryList() {
      this.showObj = {}
      this.batchObj = {}
      getCategoryTree({ shopId: this.shopId, allShow: true }).then(res => {
        this.goodsCategories = res.data.data;
      });
    },
    //上下架
    modifyStatus(value, id) {
      this.$set(this.batchObj,id,true)
      let flag = true;
      if (value == 1) {
        flag = true;
      }
      if (value == 0) {
        flag = false;
      }
      offGoodsByCate({ id: id, flag: flag }).then(res => {
        if (res.data.code == 0) {
          var _this = this;
          this.$message.success("设置成功");
          setTimeout(function() {
            _this.$set(_this.batchObj,id,false)
          }, 1000);
        }
        this.loading = true;
      }).catch(err => {
        this.$message.error("设置失败");
        var _this = this;
        setTimeout(function() {
          if (value == 1) {
            value = 0;
          }
          if (value == 0) {
            value = 1;
          }
          _this.$set(_this.batchObj,id,false)
        }, 1000);
      });
    },
    //是否显示
    changeShow(value, id) {
      console.log(value);
      // this.showObj[id] = true
      this.$set(this.showObj,id,true)
      changeCategoryStatus({
        id: id,
        categoryType: value
      }).then(res => {
        if (res.data.code == 0) {
          this.$message.success("设置成功");
          let _this = this;
          setTimeout(function() {
            _this.$set(_this.showObj,id,false)
          }, 1000);
        }
      }).catch(err => {
        this.$message.error("设置失败");
        var _this = this;
        setTimeout(function() {
          if (value == 1) {
            value = '0';
          }
          if (value == 0) {
            value = '1';
          }
          _this.$set(_this.showObj,id,false)
        }, 1000);
      });
    },
    //新增子分类
    addSubGoodsCate(row) {
      const query = {
        res: {
          shopId: row.shopId,
          parentId: row.id
        }
      };
      this.$router.push({ path: "addCategory", query: query });
    },
      //  新增父分类
      addGoodsCate() {
        if(this.shopId == '' || this.shopId == null) {
          this.$message.error('店铺不能为空')
        }else {
          const query = {
            res: {
              shopId: this.shopId
            }
          }
          this.$router.push({path: 'addCategory', query: query})
        }
      },
      //  编辑分类
      editGoodsCate(row) {
        const query = {
          res: {
            categoryId: row.id,
            shopId: this.shopId
          }

      };
      this.$router.push({ path: "editCategory", query: query });
    },
    //  删除分类
    delGoodsCate(row) {
      deleteCategory(row.id).then(res => {
        this.$message.success("删除成功");
        this.getGoodsCategoryList();
      });
    },
    //  刷新表格
    refreshTable() {
      this.getGoodsCategoryList();
    },
    //  搜索
    searchChange(params, done) {
      console.log(params);
      done();
    }
  }
};
</script>

<style lang="scss" scoped>
.search-wrap {
  margin-bottom: 20px;
}

.category-logo {
  width: 60px;
  height: 60px;
  border-radius: 6px;
}
.tool-btns {
  /*float: right;*/
  margin-left: 30px;
  display: inline-block;
}
</style>
